import { Toast } from "vant";

export default {
  state: {
    address: JSON.parse(localStorage.getItem('address') || '[]')
  },
  mutations: {
    addAddress(state, val) {
      val.address = `${val.province}${val.city}${val.county}`
      console.log(state.address.length);
      // 指定每一项的 id
      val.id = state.address.length + 1
      this.commit('setlectDefault', val)
      localStorage.setItem('address', JSON.stringify(state.address))
    },
    editAddress(state, val) { 
      const result = state.address.find((item, index) => {
        if (item.name === val.name && item.tel === val.tel && item.areaCode === val.areaCode && item.addressDetail === val.addressDetail) {
          return item
        }
      })
      if (result) {
        Toast.fail('已有此地址')
        return
      }
      state.address.splice(val.id-1 , 1 , val)
      localStorage.setItem('address', JSON.stringify(state.address))
      Toast.success('编辑成功')
    },
    setlectDefault(state, val) {
      // 查找address数组中是否含有相同项
      const result = state.address.find((item, index) => {
        if (item.name === val.name && item.tel === val.tel && item.areaCode === val.areaCode && item.addressDetail === val.addressDetail) {
          return item
        }
      })
      if (result) {
        Toast.fail('不能添加相同的地址信息')
        return
      }
      else {
        Toast.success('添加成功')
        if (!val.isDefault){
          state.address.push(val)
        }
        else{
          state.address.unshift(val)
          // 重新分配id
          let count = 1
          state.address.map((item) => {
            item.id = count
            count ++
            if(item.id !== 1){
              item.isDefault = false
            }
          })
        }
      }

      // 配置默认项  如果只有一项，则默认id为1
      if (val.id == 1) {
        val.isDefault = true
      }
    }
  }
}